<!-- 公共echarts组件 -->

<template>
  <div
    ref="chartRef"
    style="padding: 30px 0 10px 30px; box-sizing: border-box"
    :style="{ width, height }"
  ></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'

const props: any = defineProps({
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '100%',
  },
})
const emit = defineEmits(['instance'])

const chartRef = ref(null)
let chartInstance: any = null
onMounted(() => {
  emit('instance', chartInstance) // 触发 instance 事件，将 Echarts 实例暴露给父组件
})

function initEchat(option: any) {
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  if (!option.grid) {
    option.grid = {
      left: 100,
      right: 60,
      bottom: 60,
    }
  }

  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })

  chartInstance.setOption(option)
}

defineExpose({
  initEchat,
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>
